package apis

import (
	. "ding-and-xiao-yun/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

func IndexApi(c *gin.Context) {
	c.String(http.StatusOK, "It works")
}

func AddPersonApi(c *gin.Context) {
	firstName := c.Request.FormValue("first_name")
	lastName := c.Request.FormValue("last_name")
	p := Person{FirstName: firstName, LastName: lastName}
	ra, err := p.AddPerson()
	if err != nil {
		log.Fatalln(err)
	}
	msg := fmt.Sprintf("insert successful %d", ra)
	c.JSON(http.StatusOK, gin.H{
		"msg": msg,
	})
}

func GetPersonsApi(c *gin.Context) {
	p := Person{}
	persons, err := p.GetPersons()
	if err != nil {
		log.Fatalln(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"persons": persons,
	})
}

func GetPersonApi(ctx *gin.Context) {
	cid := ctx.Param("id")
	id, err := strconv.Atoi(cid)
	if err != nil {
		log.Fatalln(err)
	}
	p := Person{Id: id}
	person, err := p.GetPerson()
	if err != nil {
		fmt.Println(err)
		ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"err": err.Error()})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"person": person,
	})

}

func ModPersonApi(ctx *gin.Context) {
	cid := ctx.Param("id")
	firstName := ctx.Request.FormValue("first_name")
	lastName := ctx.Request.FormValue("last_name")
	id, err := strconv.Atoi(cid)
	if err != nil {
		log.Fatalln(err)
	}
	p := Person{Id: id, FirstName: firstName, LastName: lastName}
	err = ctx.Bind(&p)
	if err != nil {
		log.Fatalln(err)
	}
	ra, err := p.ModPerson()

	msg := fmt.Sprintf("Update person %d successful %d", p.Id, ra)

	ctx.JSON(http.StatusOK, gin.H{
		"person": msg,
	})
}

func DeletePersonApi(ctx *gin.Context) {
	cid := ctx.Param("id")
	id, err := strconv.Atoi(cid)
	if err != nil {
		log.Fatalln(err)
	}
	p := Person{Id: id}
	ra, err := p.DeletePerson()
	if err != nil {
		fmt.Println(err)
		ctx.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"err": err.Error()})
		return
	}

	msg := fmt.Sprintf("Delete person %d successful %d", id, ra)
	ctx.JSON(http.StatusOK, gin.H{
		"msg": msg,
	})
}
